package com.course.model.service;

import com.course.model.convert.BusinessConvert;
import com.course.model.dto.ChapterDto;
import com.course.model.dto.ChapterPageDto;
import com.course.model.dto.PageDto;
import com.course.model.entity.Chapter;
import com.course.model.entity.ChapterExample;
import com.course.model.mapper.ChapterMapper;
import com.course.model.util.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @PROJECT_NAME: course
 * @DESCRIPTION:
 * @Author: 涂玄武
 * @DATE: 2021/4/9 10:06
 */
@Service
public class ChapterService {

    @Resource
    private ChapterMapper chapterMapper;

    /**
     * txw 2021-04-09 获取所有大章内容
     *
     * @return
     */
    public PageDto list(ChapterPageDto chapterPageDto) {
        //pageNum:页码，pageSize:每页条数
        PageHelper.startPage(chapterPageDto.getPage(), chapterPageDto.getSize());
        ChapterExample example = new ChapterExample();
        ChapterExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(chapterPageDto.getCourseId())){
            criteria.andCourseIdEqualTo(chapterPageDto.getCourseId());
        }
        List<Chapter> chapterList = chapterMapper.selectByExample(example);
        PageInfo<Chapter> pageInfo = new PageInfo<>(chapterList);
        chapterPageDto.setTotal(pageInfo.getTotal());
        chapterPageDto.setList(BusinessConvert.INSTANCE.chaptersToDtos(chapterList));
        return chapterPageDto;
    }

    /**
     * txw 2021-04-12 新增大章
     *
     * @param chapterDto
     */
    public void saveChapter(ChapterDto chapterDto) {
        Chapter chapter = BusinessConvert.INSTANCE.dtoToChapter(chapterDto);
        if (StringUtils.isBlank(chapterDto.getId())) {
            this.insertChapter(chapter);
        } else {
            this.updateChapter(chapter);
        }
    }

    /**
     * txw 2021-04-12 更新大章
     * @param chapter
     */
    private void updateChapter(Chapter chapter){
        chapterMapper.updateByPrimaryKeySelective(chapter);
    }

    /**
     * txw 2021-04-12 新增大章
     * @param chapter
     */
    private void insertChapter(Chapter chapter){
        chapter.setId(UuidUtil.getShortUuid());
        chapterMapper.insertSelective(chapter);
    }

    /**
     * txw 2021-04-12 删除大章
     * @param id
     */
    public void deleteChapter(String id){
        chapterMapper.deleteByPrimaryKey(id);
    }
}
